package com.m1book.site;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.m1book.domain.user.Gender;
import com.m1book.domain.user.Miser;
import com.m1book.domain.user.MiserQQAccount;
import com.m1book.entity.Profiles;
import com.m1book.repositories.user.MiserRepository;

@RequestMapping("/miser")
@Controller
@SessionAttributes("currentUser")
public class ProfilesController {
	private static final Logger logger = LoggerFactory.getLogger(ProfilesController.class);
	
	@Autowired
	private MiserRepository miserRepository;
	
	@RequestMapping(value = "/profiles", method = RequestMethod.GET, produces = "text/html")
	public String showCurrentUserProfiles(@ModelAttribute("currentUser") Miser miser, Model model) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		
		Profiles profiles = new Profiles();
		profiles.setAccount(miser.getAccount());
		
		if (miser.getInfo().getBirthday() != null) {
			profiles.setBirthday(format.format(miser.getInfo().getBirthday()));
		}
		
		profiles.setEmail(miser.getInfo().getEmail());
		
		if (miser.getInfo().getGender() != null) {
			profiles.setGender(miser.getInfo().getGender().toString());
		}
		
		profiles.setNickname(miser.getInfo().getNickname());
		profiles.setQq(miser.getQqAccount().getQq());
		profiles.setRealname(miser.getInfo().getRealname());
		
		model.addAttribute("profiles", profiles);
		return "/miser/profiles";
	}
	
	@RequestMapping(value = "/profiles", method = RequestMethod.POST, produces = "text/html")
	public String modifyCurrentUserProfiles(@ModelAttribute("currentUser") Miser miser, Profiles profiles, Model model) {
		MiserQQAccount qqAccount = new MiserQQAccount();
		qqAccount.setQq(profiles.getQq());
		miser.setQqAccount(qqAccount);
		miser.getInfo().setEmail(profiles.getEmail());
		miser.getInfo().setNickname(profiles.getNickname());
		miser.getInfo().setRealname(profiles.getRealname());
		miser.getInfo().setGender(Gender.valueOf(profiles.getGender()));
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			miser.getInfo().setBirthday(sdf.parse(profiles.getBirthday()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		miserRepository.save(miser);
		
		logger.info("update miser " + miser.getAccount() + " profiles succeed.");
		
		return "myspace";
	}
}
